<?php
declare(strict_types=1);

namespace app\model;

use think\Model;
use think\facade\Cache;

class MerchantDistributionConfig extends Model
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 获取商家分销配置
     * @param int $merchantId
     * @return array
     */
    public static function getConfig(int $merchantId): array
    {
        $cacheKey = "merchant_distribution_config:{$merchantId}";
        return Cache::remember($cacheKey, function() use ($merchantId) {
            $config = self::where('merchant_id', $merchantId)->find();
            if (!$config) {
                // 不存在则创建默认配置
                $config = self::create([
                    'merchant_id' => $merchantId,
                    'distribution_enabled' => false,
                    'level1_rate' => 0,
                    'level2_rate' => 0
                ]);
            }
            return [
                'enabled' => (bool)$config->distribution_enabled,
                'level1_rate' => floatval($config->level1_rate),
                'level2_rate' => floatval($config->level2_rate)
            ];
        }, 3600);
    }

    /**
     * 计算分销佣金
     * @param int $merchantId 商家ID
     * @param float $merchantCommission 商家佣金
     * @param int $userId 用户ID
     * @return array [level1_commission, level2_commission, level1_user_id, level2_user_id]
     */
    public static function calculateCommission(int $merchantId, float $merchantCommission, int $userId): array
    {
        $config = self::getConfig($merchantId);
        if (!$config['enabled']) {
            return [0, 0, 0, 0];
        }

        // 获取用户的推荐人
        $user = User::find($userId);
        if (!$user || !$user->parent_id) {
            return [0, 0, 0, 0];
        }

        // 计算一级佣金
        $level1Commission = round($merchantCommission * $config['level1_rate'], 2);
        $level1UserId = $user->parent_id;

        // 获取二级推荐人
        $level1User = User::find($level1UserId);
        $level2Commission = 0;
        $level2UserId = 0;
        
        if ($level1User && $level1User->parent_id) {
            $level2Commission = round($merchantCommission * $config['level2_rate'], 2);
            $level2UserId = $level1User->parent_id;
        }

        return [$level1Commission, $level2Commission, $level1UserId, $level2UserId];
    }

    /**
     * 清除商家分销配置缓存
     * @param int $merchantId
     */
    public static function clearCache(int $merchantId): void
    {
        Cache::delete("merchant_distribution_config:{$merchantId}");
    }
} 